package io.github.lee.app.unsplash.repository

import io.github.lee.app.unsplash.repository.api.SearchApi
import io.github.lee.app.unsplash.repository.dao.SearchKeywordDao
import io.github.lee.app.unsplash.repository.domain.PageResponse
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.repository.domain.SearchKeyword
import io.github.lee.app.unsplash.repository.domain.UnsplashResponse
import io.github.lee.app.unsplash.repository.params.ColorFilter
import io.github.lee.app.unsplash.repository.params.OrderBy
import io.github.lee.app.unsplash.repository.params.Orientation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject

class SearchRepository @Inject constructor(
    private val dao: SearchKeywordDao,
    private val api: SearchApi
) {
    fun queryByCount(count: Int): Flow<List<SearchKeyword>> =
        dao.queryByCount(count).flowOn(Dispatchers.IO)

    fun insertKeyword(keyword: String) {
        dao.queryByWord(keyword)
        val kw = SearchKeyword(0, keyword)
        dao.insertIgnore(kw)
    }

    fun update(keyword: SearchKeyword): Int {
        return dao.update(keyword)
    }

    fun queryByKeyword(keyword: String): SearchKeyword? =
        dao.queryByWord(keyword)

    fun deleteAll() =
        dao.deleteAll()

    //===Desc:======================================================================================

    suspend fun searchPhoto(
        keyword: String,
        page: Int,
        size: Int = 10,
        orderBy: OrderBy? = null,
        orientation: Orientation? = null,
        color: ColorFilter? = null
    ): UnsplashResponse<PageResponse<Photo>> =
        api.searchPhoto(keyword, page, size, orderBy?.value, orientation?.value, color?.value)


}